﻿Option Explicit On

Public Class frmFerramentasChaves
    Private intPKChave As Integer

    Private Sub frmFerramentasChaves_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Call MontaGrid()
        With cmbTemplate
            .Clear()
            .SQL = "SELECT template, id_template FROM templates ORDER BY template ASC"
            .Reload()
        End With
        Call CancelarOperacao()
    End Sub

    Private Sub MontaGrid()
        Try
            '-- DataGridView
            With dgvChaves
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToResizeRows = False
                '.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray'-- zebrado
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .MultiSelect = False
                .ConnectionString = strMyDBString
                .TypeConnection = AnguloGridView.EnumTypeConection.SQLiteDataAdapter
                .SQL = "SELECT id_chave, nome_chave " & _
                       "FROM chaves " & _
                       "ORDER BY nome_chave"
                .AddColumn("ID", 20, False)
                .AddColumn("Nome", 150, , DataGridViewContentAlignment.MiddleLeft)
                .Reload()
            End With

            With dgvChavesItens
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToResizeRows = False
                '.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray'-- zebrado
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .MultiSelect = False
                .ConnectionString = strMyDBString
                .TypeConnection = AnguloGridView.EnumTypeConection.SQLiteDataAdapterRW
                .SQL = ""
                .AddColumn("#", 30)
                .AddColumn("ID", 0)
                .AddColumn("Nome", 0)
                .AddColumn("Tipo", 60)
                .AddColumn("Mascara", 0)
                .FillColumns()
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub tbPadrao_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tbPadrao.ItemClicked
        Try
            Select Case e.ClickedItem.Tag
                Case "IN"
                    Call NovoRegistro()
                Case "ED", "AL"
                    Call EditarDados()
                Case "GR"
                    Call GravarRegistro()
                Case "CR", "CA"
                    Call CancelarOperacao()
                Case "EX"
                    Call ApagarDados()
            End Select
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub Novoregistro()
        tbPadrao.ToolOrder("IN")
        pnlItem.Enabled = True
        txtNomeChave.Select()
    End Sub

    Private Sub EditarDados()
        Try
            intPKChave = TrataNull(dgvChaves.CurrentRow.Cells(0).Value, TypeCode.Int64)
            If intPKChave > 0 Then
                Call PuxarDados()
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub PuxarDados()
        Try
            Dim strSQL As String = "SELECT nome_chave, id_template, obs, mod11, nome_elemento_dv " & _
                                   "FROM chaves " & _
                                   "WHERE id_chave=" & intPKChave & ""
            mySQLite.Query(strSQL)
            If Not mySQLite.EOF Then
                txtNomeChave.Text = TrataNull(mySQLite.Field("nome_chave"), TypeCode.String)
                cmbTemplate.Buscar = TrataNull(mySQLite.Field("id_template"), TypeCode.Int32)
                txtObs.Text = TrataNull(mySQLite.Field("obs"), TypeCode.String)
                chkMod11.Checked = IIf(TrataNull(mySQLite.Field("mod11"), TypeCode.String) = "S", True, False)
                txtNomeElementoDV.Text = TrataNull(mySQLite.Field("nome_elemento_dv"), TypeCode.String)
                '--
                dgvChavesItens.SQL = "SELECT ordem, id_template_item, nome, tipo, mascara " & _
                     "FROM chaves_itens " & _
                     "WHERE id_chave = " & intPKChave & " " & _
                     "ORDER BY ordem ASC"
                dgvChavesItens.Reload()
                Call SomaDigitos()
                '--
                tbPadrao.ToolOrder("ED")
                pnlItem.Enabled = True
                cmbTemplate.Enabled = False
                txtNomeChave.Select()
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        Finally


        End Try
    End Sub

    Private Sub GravarRegistro()
        If IsEmpty(txtNomeChave.Text) Then
            Call MsgBox("Preencha o nome da chave!", MsgBoxStyle.Exclamation)
            txtNomeChave.Select()
            Exit Sub
        End If
        Call GravarDados()
        Call CancelarOperacao()
    End Sub

    Private Sub GravarDados()
        Try
            Dim intCount As Int16
            Dim strSQL As String = "SELECT * FROM chaves WHERE id_chave=" & intPKChave & ""
            mySQLite.Query(strSQL)
            If mySQLite.EOF Then
                mySQLite.AddNew()
                mySQLite.Field("id_template") = TrataNull(cmbTemplate.Value, TypeCode.Int32)
            End If
            mySQLite.Field("nome_chave") = TrataNull(txtNomeChave.Text, TypeCode.String)
            mySQLite.Field("obs") = TrataNull(txtObs.Text, TypeCode.String)
            mySQLite.Field("mod11") = IIf(chkMod11.Checked = True, "S", "N")
            mySQLite.Field("nome_elemento_dv") = TrataNull(txtNomeElementoDV.Text, TypeCode.String)
            mySQLite.Update()

            If intPKChave = 0 Then
                intPKChave = mySQLite.ExecuteReturn("SELECT MAX(id_chave) FROM chaves")
            End If
            '--
            With dgvChavesItens
                mySQLite.Execute("DELETE FROM chaves_itens WHERE id_chave=" & intPKChave & "")
                For intCount = 0 To .Rows.Count - 1
                    strSQL = "INSERT INTO chaves_itens(id_chave, ordem, id_template_item, nome, tipo, mascara) " & _
                             "VALUES(" & intPKChave & ", " & _
                             "'" & .TextMatrix(intCount, 0).Replace("'", "''") & "'," & _
                             "'" & .TextMatrix(intCount, 1).Replace("'", "''") & "'," & _
                             "'" & .TextMatrix(intCount, 2).Replace("'", "''") & "'," & _
                             "'" & .TextMatrix(intCount, 3).Replace("'", "''") & "'," & _
                             "'" & .TextMatrix(intCount, 4).Replace("'", "''") & "')"
                    mySQLite.Execute(strSQL)
                Next
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        Finally
        End Try
    End Sub

    Private Sub CancelarOperacao()
        Call ItemCancelarOperacao()
        Call LimpaForm(pnlItem)
        dgvChavesItens.Clear()
        tbPadrao.ToolOrder("CA")
        pnlItem.Enabled = False
        cmbTemplate.Enabled = True
        intPKChave = 0
        dgvChaves.Reload()
    End Sub

    Private Sub ApagarDados()
        Try
            If MsgBox("Apagar este lançamento?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                mySQLite.Execute("DELETE FROM chaves_itens WHERE id_chave=" & intPKChave & "")
                mySQLite.Execute("DELETE FROM chaves WHERE id_chave=" & intPKChave & "")
            End If
            Call CancelarOperacao()
        Catch ex As Exception
            Select Case Err.Number
                Case -2147467259
                    Call MsgBox("Este registro não pode ser excluído, pois está lançando em outra tela!", MsgBoxStyle.Exclamation)
                Case Else
                    Call MsgBox(Err.Description, MsgBoxStyle.Exclamation)
            End Select
            Call SendError(ex.Message, ex.StackTrace)
        Finally

        End Try
    End Sub

    Private Sub txtNomeChave_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtNomeChave.TextChanged
        lblFuncao.Text = "{?" & txtNomeChave.Text & "?}"
    End Sub

    Private Sub tbDados_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles tbDados.ItemClicked
        Try
            Select Case e.ClickedItem.Tag
                Case "IN"
                    Call ItemNovoregistro()
                Case "AL", "ED"
                    Call ItemEditarDados()
                Case "GR"
                    Call ItemGravarRegistro()
                Case "CR", "CA"
                    Call ItemCancelarOperacao()
                Case "EX"
                    Call ItemApagarDados()
            End Select
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub ItemNovoRegistro()
        gpbElementos.Enabled = True
        tbDados.ToolOrder("IN")
        txtOrdem.Select()
    End Sub

    Private Sub ItemEditarDados()
        With dgvChavesItens
            txtOrdem.Text = TrataNull(.TextMatrix(.CurrentRow.Index, 0), TypeCode.Int16, txtOrdem.Mascara)
            txtID.Text = TrataNull(.TextMatrix(.CurrentRow.Index, 1), TypeCode.String)
            txtNome.Text = TrataNull(.TextMatrix(.CurrentRow.Index, 2), TypeCode.String)
            txtTipo.Text = TrataNull(.TextMatrix(.CurrentRow.Index, 3), TypeCode.String)
            txtMascara.Text = TrataNull(.TextMatrix(.CurrentRow.Index, 4), TypeCode.String)
            '--
            tbDados.ToolOrder("ED")
            gpbElementos.Enabled = True
        End With
    End Sub

    Private Sub ItemGravarRegistro()
        If IsEmpty(txtNome.Text) Then
            Call MsgBox("Elemento do template não foi preechido!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If
        Call LancarGrid()
        tbDados.ToolOrder("CA")
        gpbElementos.Enabled = False
        Call LimpaForm(gpbElementos)
    End Sub

    Private Sub LancarGrid()
        Dim intCount As Int16, blnFound As Boolean
        With dgvChavesItens
            For intCount = 0 To .Rows.Count - 1
                If txtID.Text = TrataNull(.TextMatrix(intCount, 1), TypeCode.String) Then
                    blnFound = True
                    Exit For
                End If
            Next
            If blnFound = False Then
                .Rows.Add()
                intCount = .Rows.Count - 1
            End If
            .TextMatrix(intCount, 0) = TrataNull(txtOrdem.Text, TypeCode.Int16, txtOrdem.Mascara)
            .TextMatrix(intCount, 1) = TrataNull(txtID.Text, TypeCode.String)
            .TextMatrix(intCount, 2) = TrataNull(txtNome.Text, TypeCode.String)
            .TextMatrix(intCount, 3) = TrataNull(txtTipo.Text, TypeCode.String)
            .TextMatrix(intCount, 4) = TrataNull(txtMascara.Text, TypeCode.String)
            '--
            .Sort(.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
        End With
        Call SomaDigitos()
    End Sub

    Private Sub ItemCancelarOperacao()
        Call LimpaForm(gpbElementos)
        gpbElementos.Enabled = False
        tbDados.ToolOrder("CA")
    End Sub

    Private Sub ItemApagarDados()
        With dgvChavesItens
            If .CurrentRow.Index < 0 Then Exit Sub
            If MsgBox("Deseja realmente apagar este item?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                .Rows.Remove(.CurrentRow)
                Call ItemCancelarOperacao()
            End If
        End With
    End Sub

    Private Sub txtID_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtID.Validating
        Try
            If IsEmpty(txtID.Text) Then Exit Try
            txtID.Text = txtID.Text.ToString.Trim
            Dim strTam As String = "", intReplace As Int16
            Dim strSQL As String = "SELECT nome, tipo, tam " & _
                                   "FROM templates_itens " & _
                                   "WHERE id_template= " & cmbTemplate.Value & " " & _
                                   "AND id='" & txtID.Text & "' "
            mySQLite.Query(strSQL)
            If Not mySQLite.EOF Then
                txtNome.Text = TrataNull(mySQLite.Field("nome"), TypeCode.String)
                txtTipo.Text = TrataNull(mySQLite.Field("tipo"), TypeCode.String)
                Select Case Trim(TrataNull(mySQLite.Field("tam"), TypeCode.String))
                    Case "-", "", "0"

                    Case Else
                        Select Case TrataNull(mySQLite.Field("tipo"), TypeCode.String)
                            Case "N"
                                Dim mtzTam() As String = Split(TrataNull(mySQLite.Field("tam"), TypeCode.String), "-")
                                For intTam As Int16 = 0 To mtzTam.Length - 1
                                    intReplace = CInt(mtzTam(intTam))
                                Next
                                txtMascara.Text = Strings.StrDup(intReplace, "0")
                        End Select
                End Select
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub chkMod11_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkMod11.CheckedChanged
        If chkMod11.Checked = False Then
            txtNomeElementoDV.Enabled = False
            txtNomeElementoDV.Text = String.Empty
        Else
            txtNomeElementoDV.Enabled = True
        End If
        Call SomaDigitos()
    End Sub

    Private Sub txtNomeElementoDV_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtNomeElementoDV.Validating
        Try
            If IsEmpty(txtNomeElementoDV.Text) Then Exit Try
            txtNomeElementoDV.Text = txtNomeElementoDV.Text.ToString.Trim
            Dim strSQL As String = "SELECT nome, tipo " & _
                                   "FROM templates_itens " & _
                                   "WHERE id_template= " & cmbTemplate.Value & " " & _
                                   "AND nome='" & txtNomeElementoDV.Text & "' "
            mySQLite.Query(strSQL)
            If mySQLite.EOF Then
                Call MsgBox("Elemento não encontrado no template, verifique a grafia!", MsgBoxStyle.Exclamation)
                e.Cancel = True
            End If
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub SomaDigitos()
        Dim intDig As Int16
        With dgvChavesItens
            '--
            For intCount As Int16 = 0 To .RowCount - 1
                intDig = intDig + Len(.TextMatrix(intCount, 4))
            Next
            lblDigitos.Text = Format(intDig + IIf(chkMod11.Checked = True, 1, 0), "00") & " Dígitos"
        End With
    End Sub
End Class